package com.qianli.cashmama.trade.common.utils.signature;

import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * 压缩图片
 *
 * @author liuming
 * Created on 下午11:16 2018/8/26.
 */
public class ImageUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImageUtil.class);

    /**
     * 压缩图片
     *
     * @param imagePath
     * @param quality
     * @return
     * @throws IOException
     */
    public static byte[] compressPic(String imagePath, float quality) throws IOException {
        byte[] inByte = null;
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Thumbnails.of(new URL(imagePath)).scale(1f).outputFormat("jpg").outputQuality(quality).toOutputStream(out);
            inByte = out.toByteArray();
            out.close();
        } catch (IOException ex) {
            LOGGER.info("*** 压缩图片异常 ***");
        }
        return inByte;
    }


    public static void main(String[] args) throws Exception {
        createImage("Sign by master ming buster", new Font(null, Font.BOLD, 10), new File(
                "/Users/liuming/Downloads/a.png"), 40 * 10, 100);
    }

    /**
     * 根据str,font的样式以及输出文件目录
     *
     * @param str     字符串
     * @param font    字体
     * @param outFile 输出文件位置
     * @param width   宽度
     * @param height  高度
     * @throws Exception
     */
    public static void createImage(String str, Font font, File outFile,
                                   Integer width, Integer height) throws Exception {
        // 创建图片
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_BGR);
        Graphics g = image.getGraphics();
        g.setClip(0, 0, width, height);
        g.setColor(Color.white);
        // 先用黑色填充整张图片,也就是背景
        g.fillRect(0, 0, width, height);
        // 在换成红色
        g.setColor(Color.black);
        // 设置画笔字体
        g.setFont(font);


        // 画出字符串
        g.drawString(str, 10, 20);
        g.drawString(str, 10, 50);
        g.drawString(str, 10, 80);
        g.dispose();
        // 输出png图片
        ImageIO.write(image, "png", outFile);
    }

}
